import React, { useEffect, useRef, useState } from "react";
import { Image as MyImage, NavBar, Toast } from "antd-mobile";
import { useNavigate, useLocation } from "react-router-dom";
import { useCountdown } from "../../../context/MemberContext";
import $fetch from "../../../utils/app/$fetch";
import { ReactComponent as QueueIcon } from '../../../asset/imgs/queue.svg';
import { ReactComponent as TimeIcon } from '../../../asset/imgs/time.svg';
import "./style.scss";


const iconColor = getComputedStyle(document.documentElement)
  .getPropertyValue('--logoColor')
  .trim();

const formatTime = (remainingTime: any) => {
  const minutes = Math.floor(remainingTime / (1000 * 60));
  const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
  const milliseconds = Math.floor((remainingTime % 1000) / 10);
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
};

export default function Participates() {
  const { setCountdowns, stopCountdown }: any = useCountdown();
  const navigate = useNavigate();
  const location: any = useLocation();
  const intervalRefs: any = useRef();
  const memberRef: any = useRef({});
  // eventType为2时是电切会
  const { eventId, eventType }: any = location?.state?.detail;
  const [members, setMembers] = useState<any>([]);
  const savedCountdowns: any = localStorage.getItem("countdowns");
  const countdowns: any =  savedCountdowns ? JSON.parse(savedCountdowns) : {};

  useEffect(() => {
    initPage();
    intervalQuery();
  }, []);

  const initPage = async () => {
    const res: any = await $fetch(
      `/line/list/${eventId}`,
      {},
      { loading: false }
    );
    setMembers(res);
  };

  const intervalQuery = async () => {
    intervalRefs.current = setInterval(async () => {
      const res: any = await $fetch(
        `/line/list/${eventId}`,
        {},
        { loading: false }
      );
      setMembers(res);
    }, 5000);
  };

  useEffect(() => {
    handleCutdowns();
    return () => {
      clearInterval(intervalRefs.current);
      Object.keys(countdowns).forEach((id: any) => {
        clearInterval(memberRef.current[id]);
      });
    };
  }, []);

  const handleCutdowns = () => {
    Object.keys(countdowns).forEach((id: any) => {
      if (!countdowns[id]?.endTime || countdowns[id]?.endTime === 0 || countdowns?.[id]?.endTime < Date.now()) {
        return;
      } else {
        memberRef.current[id] = setInterval(async () => {
          if (countdowns?.[id]?.endTime >= Date.now()) {
            // 正在计时
            const status = formatTime(countdowns?.[id]?.endTime - Date.now());
            setCountdowns((prev: any) => {
              const newCountdowns = {
                ...prev,
                [id]: {
                  ...countdowns[id],
                  status,
                },
              };
              localStorage.setItem('countdowns', JSON.stringify(newCountdowns))
              return newCountdowns;
            });
          } else {
            // 计时到时间，状态为超时，关闭定时器，删除排队人员
            const memberId = countdowns[id].memberId;
            const customerId = countdowns[id]?.customerId;
            clearInterval(memberRef.current[id]);
            // stopCountdown(eventId, memberId);
            setCountdowns((prev: any) => {
              const newCountdowns = {
                ...prev,
                [id]: { ...countdowns[id], endTime: 0 },
              };
              localStorage.setItem('countdowns', JSON.stringify(newCountdowns))
              return newCountdowns;
            });
            await $fetch(
              `/operation/deleteLine/${customerId}/${memberId}?eventId=${eventId}`,
              {},
              { loading: false, method: "post", noGroupId: "no" }
            );
          }
        }, 10);
      }
    });
  };

  const back = () => {
    navigate("/activity/list");
  };

  return (
    <div className="container_activity_participates">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => back()}
      >
        排队详情
      </NavBar>
      <ul className="that_queue_list activity_public">
        {members?.map((member: any) => {
          const id = `${eventId}_${member?.memberId}`;

          return (
            <li
              className="that_item"
              key={member?.memberId}
              onClick={() => {
                if (member?.lineNum == null) {
                  Toast.show("无人排队");
                  return;
                };
                if (eventType === "2") {
                  navigate("/activity/queue", {
                    state: { detail: { ...member, eventId, eventType } },
                  });
                } else {
                  let url = "/activity/queue";
                  let timing = false;
                  if (countdowns[id]?.endTime) {
                    url = "/activity/timing";
                    timing = true;
                  }
                  navigate(url, {
                    state: { detail: { ...member, eventId }, timing },
                  });
                }
              }}
            >
              <div className="img_wraper">
                <MyImage
                  src={member?.memberFormulPhoto}
                  fit="cover"
                  width="3.95rem"
                  height="3.95rem"
                  lazy={true}
                />
              </div>

              <div className="item_content_wraper">
                <div className="name">{member?.memberName}</div>
                <div className="center">
                  <div className="queue">
                    <div>
                      <QueueIcon width={50} height={50} fill={iconColor}/>
                      <span>排队人数:</span>

                    </div>
                    <span>{member?.lineNum || 0}</span>
                  </div>
                  {eventType !== "2" && (
                    <div className="wait">
                      <div>
                        <TimeIcon width={50} height={50} fill={iconColor}/>
                        <span>计时时间:</span>
                      </div>
                      {!countdowns?.[id] && <span className="free">空闲中</span> }
                      {countdowns?.[id]?.endTime > 0 && <span className="timing">{countdowns?.[id]?.status}</span>}
                      {countdowns?.[id]?.endTime === 0 && <span className="expire">超时</span>}
                    </div>
                  )}
                </div>
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
